//
//  NetManager.swift
//  Eternity
//
//  Created by zhengwei on 2017/1/4.
//  Copyright © 2017年 ZhengWei. All rights reserved.
//

import Foundation
import UIKit
import Alamofire
import SwiftyJSON

private let NetworkRequestShareInstance = NetManager()

class NetManager {
    class var sharedInstance : NetManager {
        return NetworkRequestShareInstance
    }
}
extension NetManager {
    //MARK: - GET 请求
    //    let tools : NetworkRequest.shareInstance!
    
    func getRequest(urlString: String, params : [String : Any], success : @escaping (_ response : [String : AnyObject])->(), failture : @escaping (_ error : Error)->()) {
        
        //使用Alamofire进行网络请求时，调用该方法的参数都是通过getRequest(urlString， params, success :, failture :）传入的，而success传入的其实是一个接受           [String : AnyObject]类型 返回void类型的函数
        
        Alamofire.request(urlString, method: .get, parameters: params)
            .responseJSON { (response) in/*这里使用了闭包*/
                //当请求后response是我们自定义的，这个变量用于接受服务器响应的信息
                //使用switch判断请求是否成功，也就是response的result
                switch response.result {
                case .success(let value):
                    //当响应成功是，使用临时变量value接受服务器返回的信息并判断是否为[String: AnyObject]类型 如果是那么将其传给其定义方法中的success
                    //                    if let value = response.result.value as? [String: AnyObject] {
                    success(value as! [String : AnyObject])
                    //                    }
                    let json = JSON(value)
                    print(json)
                    
                case .failure(let error):
                    failture(error)
                    print("error:\(error)")
                }
        }
        
    }
    //MARK: - POST 请求
    func postRequest(urlString : String, params : [String : Any], success : @escaping (_ response : [String : AnyObject])->(), failture : @escaping (_ error : Error)->()) {
        
        var string = "https://api.harmay.com"
        string = string.appending(urlString)
        
        var dataDic = params
        let infoDictionary = Bundle.main.infoDictionary
        let version: String? = infoDictionary!["CFBundleVersion"] as! String?
        dataDic["version"] = version
        dataDic["platform"] = "2";
        dataDic["channel"] = "Appstore";
        let paramsStr = toJSONString(dict: dataDic as [String : AnyObject])
        let encryptStr = ContentSecurity.encrypt(paramsStr)
        
        var postDic = Dictionary<String, Any>()
        postDic["params"] = encryptStr
        
        let date = NSDate()
        let timeInterval = Int(date.timeIntervalSince1970 * 1000)
        let dateStr = "\(timeInterval)"
        
        Alamofire.request(string, method: HTTPMethod.post, parameters: postDic, encoding: URLEncoding.default, headers: ["k":GateSecurity.encrypt(dateStr)]).responseJSON { (response) in
            switch response.result{
            case .success:
                if let value = response.result.value as? [String: AnyObject] {
                    let valueStr = ContentSecurity.decrypt(value["response"] as! String!)
                    let valueDic = self.toDictionary(jsonStr: valueStr!)
                    success(valueDic as [String : AnyObject])
                    let json = JSON(valueDic)
                    print(json)
                }
            case .failure(let error):
                failture(error)
                print("error:\(error)")
            }
        }
        
        
        
        
        
    }
    
    //MARK: - 照片上传
    ///
    /// - Parameters:
    ///   - urlString: 服务器地址
    ///   - params: ["flag":"","userId":""] - flag,userId 为必传参数
    ///        flag - 666 信息上传多张  －999 服务单上传  －000 头像上传
    ///   - data: image转换成Data
    ///   - name: fileName
    ///   - success:
    ///   - failture:
    func upLoadImageRequest(urlString : String, params:[String:String], data: [Data], name: [String],success : @escaping (_ response : [String : AnyObject])->(), failture : @escaping (_ error : Error)->()){
        
        let headers = ["content-type":"multipart/form-data"]
        
        Alamofire.upload(
            multipartFormData: { multipartFormData in
                //666多张图片上传
                let flag = params["flag"]
                let userId = params["userId"]
                
                multipartFormData.append((flag?.data(using: String.Encoding.utf8)!)!, withName: "flag")
                multipartFormData.append( (userId?.data(using: String.Encoding.utf8)!)!, withName: "userId")
                
                for i in 0..<data.count {
                    multipartFormData.append(data[i], withName: "appPhoto", fileName: name[i], mimeType: "image/png")
                }
        },
            to: urlString,
            headers: headers,
            encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.responseJSON { response in
                        if let value = response.result.value as? [String: AnyObject]{
                            success(value)
                            let json = JSON(value)
                            print(json)
                        }
                    }
                case .failure(let encodingError):
                    print(encodingError)
                    failture(encodingError)
                }
        }
        )
    }
    
    func toJSONString(dict :[String : AnyObject])->String{
        
        let data = try? JSONSerialization.data(withJSONObject: dict, options: [])
        let str = String(data:data!, encoding: String.Encoding.utf8)!
        return str
    }
    
    func toDictionary(jsonStr:String) -> [String : AnyObject] {
        let data = jsonStr.data(using: String.Encoding.utf8)! as Data
        let dictionary = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers)
        return dictionary as! [String : AnyObject]
    }
}
